$(document).ready(function(){
    initCommonFunction();
    initUpload();
    refreshAjaxModal();
    autoSlug();
    scrollToTop();
    $("table").tablesorter();
    if(typeof init == 'function'){ init(); }
});

function check_login(info){
    if(info.code == 1000){
        window.location = info.login_href;
    }
}

function flushCKEditor(){
    for (instance in CKEDITOR.instances) {
        CKEDITOR.instances[instance].updateElement();
    }
}

function scrollToTop(){
    $(window).scroll(function(){
        if ($(this).scrollTop() > 50) {
            $('.scrollup').fadeIn();
        } else {
            $('.scrollup').fadeOut();
        }
    });

    $('.scrollup').click(function(){
        htmlScrollToTop();
        return false;
    });
}

function htmlScrollToTop(){
    $("html, body").animate({ scrollTop: 0 }, 600);
}

function toggleProgressModal(isShow){
    if(isShow){
        $('#modal-progress').modal();
    } else {
        $('#modal-progress').modal('hide');
    }
}

function refreshAjaxModal(){
    $('body').on('hidden.bs.modal', '.modal', function () {
        $(this).removeData('bs.modal');
    });
}

function showPanelUpdate(table, func){
    $(table + ' tr.can-edit').dblclick(function(event){
        event.stopPropagation();
        $('tr.tr-update-temp').remove();
        $('tr.editting').removeClass('hidden');
        var html = func($(this));
        $(this).addClass('hidden').addClass('editting').after(html);
        return false;
    });

    $(document.body).on('click', '.btn-cancel-update', function(){
        cancelUpdate();
    });
}

function cancelUpdate(){
    $('tr.tr-update-temp').remove();
    $('tr.editting').removeClass('hidden').removeClass('editting');
}

function submitUpdate(successFunc){
    $(document.body).on('click', '.btn-submit-update', function(){
        var form = $(this).closest('form');
        $.ajax({
            url: form.parents('table').attr('data-href'),
            type: form.attr('method'),
            data: form.serialize(),
            beforeSend: function(){
                $('#modal-progress').modal();
                $('#flg_message h4.message-title').html('');
                $('#flg_message div.message-text').html('');
            },
            success:function(data){
                check_login(data);
                if(data.code===1){
                    $('#flg_message').removeClass('alert-danger').addClass('alert-success');
                    if(form.attr('data-callback') && form.attr('data-callback')==1){
                        successFunc(data);
                    } else {
                        successFunc();
                    }
                    cancelUpdate();
                } else {
                    $('#flg_message').addClass('alert-danger').removeClass('alert-success');
                    $('#flg_message h4.message-title').html(data.title);
                }
                $('#flg_message div.message-text').html(data.text);
                $('#modal-progress').modal('hide');
            }
        }).done(function(){
            showMessage();
        });
    });
}

function submitUpdateForm(btn, callback){
    $(document.body).on('click', btn, function(){
        flushCKEditor();
        var form = $(this).closest('form');
        $.ajax({
            url: form.attr('action'),
            type: form.attr('method'),
            data: form.serialize(),
            beforeSend: function(){
                $('#modal-progress').modal();
                $('#flg_message h4.message-title').html('');
                $('#flg_message div.message-text').html('');
            },
            success:function(data){
                check_login(data);
                if(data.code===1){
                    $('#flg_message').removeClass('alert-danger').addClass('alert-success');
                    if(callback!==undefined){
                        var attr = form.attr('data-callback');
                        if(typeof attr === 'undefined' || attr==0){
                            callback();
                        } else {
                            if(attr==1){ callback(data); }
                        }
                    }
                    cancelUpdate();
                } else {
                    $('#flg_message').addClass('alert-danger').removeClass('alert-success');
                    $('#flg_message h4.message-title').html(data.title);
                }
                $('#flg_message div.message-text').html(data.text);
                $('#modal-progress').modal('hide');
            }
        }).done(function(){
            showMessage();
        });
    });
}

function changeState(url, data, callback){
    $.ajax({
        url: url,
        type: 'POST',
        dataType: 'json',
        data: data,
        success: function(data) {
            check_login(data);
            if(data.code===1){
                $('#flg_message').removeClass('alert-danger').addClass('alert-success');
                $('#flg_message h4.message-title').html('');
            } else {
                $('#flg_message').addClass('alert-danger').removeClass('alert-success');
                $('#flg_message h4.message-title').html(data.title);
            }
            $('#flg_message div.message-text').html(data.text);
            if(typeof callback=='function'){
                callback(data);
            }
        }
    }).done(function(){
        showMessage();
    });
}

function showMessage(){
    $('#flg_message').stop().show();
    if(!$('#flg_message').hasClass('alert-danger')){
        setTimeout(function() { $('#flg_message').stop().slideUp() }, 2000);
    }
    $('#flg_message .close').click(function(){
        $('#flg_message').stop().slideUp();
    });
}

function autoSlug(){
    $(document.body).on('keyup', '.auto-slug', function(){
        var str = $(this).val().trim().toLowerCase();
        if(str!=''){
            str = str.replace(/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ/g,"a");
            str = str.replace(/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ/g,"e");
            str = str.replace(/ì|í|ị|ỉ|ĩ/g,"i");
            str = str.replace(/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ/g,"o");
            str = str.replace(/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ/g,"u");
            str = str.replace(/ỳ|ý|ỵ|ỷ|ỹ/g,"y");
            str = str.replace(/đ/g,"d");
            str = str.replace(/!|@|%|\^|\*|\(|\)|\+|\=|\<|\>|\?|\/|,|\.|\:|\;|\'| |\"|\&|\#|\[|\]|~|$|_/g,"-");
            str = str.replace(/-+-/g,"-"); //thay thế 2- thành 1-
            str = str.replace(/^\-+|\-+$/g,"");
            str = str.toLowerCase();
            str = str.replace(/ /g, '-');
        }
        var follow_ctr = $(this).closest('form').find($(this).attr('follow-ctr'));
        $(follow_ctr).val(str);
    });
}